const conn = require('../app/database')

class CommentService {
	async create(momentId, content, userId) {
		const statement = `INSERT INTO comment(moment_id, content, user_id) VALUES (?,?,?);`
		const result = await conn.execute(statement, [momentId, content, userId])
		return result[0]
  }
  
  // 评论某条发表的评论
  async reply(commentId, momentId, content, userId) {
    const statement = `INSERT INTO comment(moment_id, content, user_id, comment_id) VALUES (?,?,?,?);`
		const result = await conn.execute(statement, [momentId, content, userId, commentId])
		return result[0]
  }

  async update(commentId, content) {
    const statement = `UPDATE comment SET content = ? WHERE id = ?;`
    const result = await conn.execute(statement, [content, commentId])
    return result[0]
  }

  async remove(commentId) {
    const statement = `DELETE FROM comment WHERE id = ?;`
    const result = await conn.execute(statement, [commentId])
    return result[0]
  }

  async getCommentsByMomentId(momentId) {
    const statement = `
      SELECT 
        c.id id, c.content content, c.createAt createTime, c.comment_id commentId,
        JSON_OBJECT('id', u.id, 'name', u.name) user
      FROM comment c
      LEFT JOIN user u ON c.user_id = u.id
      WHERE moment_id = ?;
    `
    const result = await conn.execute(statement, [momentId])
    return result[0]
  }
}

module.exports = new CommentService()
